package com.shanu.apps.details;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.apps.essentials.ConsumeWebService;
import com.apps.realtyportal.LoginActivity;
import com.apps.realtyportal.MultipleSearching;
import com.apps.realtyportal.MultipleSearching2;
import com.apps.realtyportal.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;

import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.Gallery.LayoutParams;
import android.widget.ImageButton;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;
import com.forimageandlist.*;
import com.jason.apps.alert.AlertDialogFragment;
import com.jason.apps.buyer.Buyer;
import com.jason.apps.buyer.Favorites;
import com.jason.apps.dashboard.EditProperty;
import com.jason.apps.fromdashboard.ForRent;
import com.jason.apps.fromdashboard.ForSale;
import com.jason.apps.fromdashboard.MyProperty;
import com.jason.apps.notify.GMailSender;

 
@SuppressWarnings("deprecation")
public class ShowPropertyDetail extends SherlockFragment implements
        AdapterView.OnItemClickListener, ViewSwitcher.ViewFactory {
 
	int curIndex=0;
	int downX,upX;

	private ImageView call;
    private ImageView like;
    private ImageView main_pic;
    private TextView fav;
    private TextView title;
    private TextView price;
    private TextView type;
    private TextView description;
    private TextView agent;
    private TextView address;
    private TextView contact;
    private TextView emailadd;
    Gallery g;
    String mobilenumber;
    String landline;
    String contacts;
    String email;
    String name;
    String status;
    
    private LinearLayout l;
    private LinearLayout lcall;
    
    ConsumeWebService consume;
    public final static String ARG_POSITION = "position";
    int mCurrentPosition = -1;
    SherlockFragmentActivity fa;
    public ImageLoader imageLoader;
    int prop_id=0;
    int property_id=0;

	Context appContext;
	HashMap<String, String> map;
	Bitmap[] bitmapimage;
	static ArrayList<String> images;
	
		    
    
    @Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    	fa = (SherlockFragmentActivity) super.getActivity();
		if (savedInstanceState != null) {
            mCurrentPosition = savedInstanceState.getInt(ARG_POSITION);
        }
		
		images=new ArrayList<String>();
		consume=new ConsumeWebService();
		
		View view=inflater.inflate(R.layout.propertyshowdetail, container, false);
 
       // mSwitcher = (ImageSwitcher)view.findViewById(R.id.switcher);
        like=(ImageView)view.findViewById(R.id.detail_favorites);
        fav=(TextView)view.findViewById(R.id.detail_textfavorites);
        main_pic=(ImageView)view.findViewById(R.id.imageView1);
        title=(TextView)view.findViewById(R.id.detail_title);
        price=(TextView)view.findViewById(R.id.detail_price);
        type=(TextView)view.findViewById(R.id.detail_type);
        agent=(TextView)view.findViewById(R.id.detail_agent);
        address=(TextView)view.findViewById(R.id.detail_address);
        contact=(TextView)view.findViewById(R.id.detail_contact);
        emailadd=(TextView)view.findViewById(R.id.detail_email);
        call=(ImageView)view.findViewById(R.id.detail_call);
        description=(TextView)view.findViewById(R.id.detail_description);
        l=(LinearLayout)view.findViewById(R.id.layout_favorites);
        lcall=(LinearLayout)view.findViewById(R.id.layout_call);
        
       /* mSwitcher.setFactory(this);
        mSwitcher.setInAnimation(AnimationUtils.loadAnimation(getActivity(),
                android.R.anim.fade_in));
        mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(getActivity(),
                android.R.anim.fade_out));*/
        imageLoader=new ImageLoader(getActivity().getApplicationContext());
        //showGallery(mCurrentPosition);
        call.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent=new Intent(Intent.ACTION_DIAL);
				intent.setData(Uri.parse("tel:"+mobilenumber));
				startActivity(intent);
			}
		});
        like.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new Add().execute();
			}
		});
        fav.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new Add().execute();
			}
		});
        
       g = (Gallery)view.findViewById(R.id.gallery);
        g.setOnItemClickListener(this);
        
        if(LoginActivity.PersonType.equals("Agent")){
        	l.setVisibility(View.GONE);
        	lcall.setVisibility(View.GONE);
        }
        else if((LoginActivity.PersonType.equals("Administrator"))){
        	l.setVisibility(View.GONE);
        	//lcall.setVisibility(View.GONE);
        }
        return view;
    }
    
    @Override
    public void onStart() {
        super.onStart();
        
        Bundle args = getArguments();
        
        if (args != null) {
        	
        	if(args.getString("running").equals("sale")){
        	updateViewSale(args.getInt(ARG_POSITION));	
        	}
        	else if(args.getString("running").equals("rent")){
            	updateViewRent(args.getInt(ARG_POSITION));	
            }
        	else if(args.getString("running").equals("myprop")){
            	updateViewMyProp(args.getInt(ARG_POSITION));	
            }
        	else if(args.getString("running").equals("favorites")){
        		updateViewFavorites(args.getInt(ARG_POSITION));	
        	}
        	else{
        		updateViewShowDetail(args.getInt(ARG_POSITION));
        	}

            new loadImage().execute();
            
        } else if (mCurrentPosition != -1) {
        	
        	if(args.getString("running").equals("sale")){
        		updateViewSale(mCurrentPosition);
            	}
            	else if(args.getString("running").equals("rent")){
            		 updateViewRent(mCurrentPosition);
                }
            	else if(args.getString("running").equals("myprop")){
            		updateViewMyProp(mCurrentPosition);	
                }
            	else if(args.getString("running").equals("favorites")){
            		updateViewFavorites(args.getInt(ARG_POSITION));	
            	}
            	else{
            		updateViewShowDetail(args.getInt(ARG_POSITION));
            	}

            new loadImage().execute();
        }
        
    }
	@Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(ARG_POSITION, mCurrentPosition);
    }
	public void executeFavorites(){
		new Add().execute();
	}
	
public void updateViewFavorites(int position){
		
		HashMap<String, String> map = Favorites.mylist.get(position);
		title.setText("Name: "+ map.get("property_name"));
		price.setText("Price: "+"Php "+map.get(Favorites.KEY_PRICE));
		type.setText("Type: "+map.get(Favorites.KEY_TYPE));
		description.setText(map.get(Favorites.KEY_DESCRIPTION));
		address.setText("Adrress: "+ map.get(Favorites.KEY_ADDRESS));
		name=map.get("firstname")+" "+map.get("lastname");
		agent.setText("Agent Name: "+ name);
		prop_id=Integer.parseInt(map.get(Favorites.KEY_ID));
		mobilenumber=(map.get("mobile"));
		email=(map.get("email"));
		contact.setText(""+email);
		contacts=(map.get("contacts"));
		mobilenumber=(map.get("mobile"));
		landline=(map.get("landline"));
		email=(map.get("email"));
		contact.setText("Contacts: "+contacts);
		emailadd.setText("Email Address: "+email);
	    imageLoader.DisplayImage(map.get("image"), main_pic);
	    status=map.get("status");
	    
	    if(status.equals("Sold")){
	    	
	    	l.setVisibility(View.VISIBLE);
        	//lcall.setVisibility(View.VISIBLE);
	    }
	    
    	mCurrentPosition = position;
    	   	    	
	}

public void updateViewSale(int position){
		
		HashMap<String, String> map = ForSale.mylist.get(position);
		title.setText("Name: "+ map.get(ForSale.KEY_NAME));
		price.setText("Price: "+"Php "+map.get(ForSale.KEY_PRICE));
		type.setText("Type: "+map.get(ForSale.KEY_TYPE));
		description.setText(map.get(ForSale.KEY_DESCRIPTION));
		address.setText(map.get(ForSale.KEY_ADDRESS));
		name=map.get("firstname")+" "+map.get("lastname");
		agent.setText("Agent: "+ name);
		prop_id=Integer.parseInt(map.get(ForSale.KEY_ID));
		mobilenumber=(map.get("mobile"));
		email=(map.get("email"));
		contacts=(map.get("contacts"));
		mobilenumber=(map.get("mobile"));
		landline=(map.get("landline"));
		email=(map.get("email"));
		contact.setText("Contacts: "+contacts);
		emailadd.setText("Email Address: "+email);
	    imageLoader.DisplayImage(map.get("image"), main_pic);
	    
    	mCurrentPosition = position;   	
	}

public void updateViewRent(int position){
	
	HashMap<String, String> map = ForRent.mylist.get(position);
	title.setText("Name: "+map.get("property_name"));
	price.setText("Price: "+"Php "+ map.get(ForRent.KEY_PRICE));
	type.setText("Type: "+map.get(ForRent.KEY_TYPE));
	description.setText(map.get(ForRent.KEY_DESCRIPTION));
	name=map.get("firstname")+" "+map.get("lastname");
	address.setText("Address: "+map.get(ForRent.KEY_ADDRESS));
	agent.setText("Agent: " +name);
	prop_id=Integer.parseInt(map.get(ForRent.KEY_ID));
	mobilenumber=(map.get("mobile"));
	email=(map.get("email"));
	contacts=(map.get("contacts"));
	mobilenumber=(map.get("mobile"));
	landline=(map.get("landline"));
	email=(map.get("email"));
	contact.setText("Contacts: "+contacts);
	emailadd.setText("Email Address: "+email);
    imageLoader.DisplayImage(map.get("image"), main_pic);
    
	mCurrentPosition = position;
	   	    	
}
public void updateViewMyProp(int position){
	
	HashMap<String, String> map = MyProperty.mylist.get(position);
	title.setText("Name: "+ map.get("property_name"));
	price.setText("Price: "+"Php "+map.get(MyProperty.KEY_PRICE));
	type.setText("Type: "+map.get(MyProperty.KEY_TYPE));
	description.setText(map.get(MyProperty.KEY_DESCRIPTION));
	name=map.get("firstname")+" "+map.get("lastname");
	address.setText("Address:"+map.get(MyProperty.KEY_ADDRESS));
	agent.setText("Agent: " + name);
	prop_id=Integer.parseInt(map.get(MyProperty.KEY_ID));
	mobilenumber=(map.get("mobile"));
	email=(map.get("email"));
	contacts=(map.get("contacts"));
	mobilenumber=(map.get("mobile"));
	landline=(map.get("landline"));
	email=(map.get("email"));
	contact.setText("Contacts: "+contacts);
	emailadd.setText("Email Address: "+email);
    imageLoader.DisplayImage(map.get("image"), main_pic);
    
	mCurrentPosition = position;
	   	    	
}
public void updateViewShowDetail(int position){
	
	HashMap<String, String> map = EditProperty.mylist.get(position);
	title.setText("Name: "+ map.get("property_name"));
	price.setText("Price: "+"Php "+map.get(EditProperty.KEY_PRICE));
	type.setText("Type: "+map.get(EditProperty.KEY_TYPE));
	description.setText(map.get(EditProperty.KEY_DESCRIPTION));
	name=map.get("name");
	address.setText("Address:"+map.get(EditProperty.KEY_ADDRESS));
	agent.setText("Agent: " + name);
	prop_id=Integer.parseInt(map.get(EditProperty.KEY_ID));
	contacts=(map.get("contacts"));
	mobilenumber=(map.get("mobile"));
	landline=(map.get("landline"));
	email=(map.get("email"));
	contact.setText("Contacts: "+contacts);
	emailadd.setText("Email Address: "+email);
    imageLoader.DisplayImage(map.get("image"), main_pic);
    
	mCurrentPosition = position;
	   	    	
}


public void updateViewFromBaloon(int position){
	
	HashMap<String, String> map = MultipleSearching2.mylist.get(position);
	title.setText("Name: "+ map.get("property_name"));
	price.setText("Price: "+map.get(MultipleSearching2.KEY_PRICE));
	type.setText("Type: "+map.get(MultipleSearching2.KEY_TYPE));
	description.setText(map.get(MultipleSearching2.KEY_DESCRIPTION));
	name=map.get("firstname")+" "+map.get("lastname");
	address.setText("Address:"+map.get(MultipleSearching2.KEY_ADDRESS));
	agent.setText("Agent: " + name);
	prop_id=Integer.parseInt(map.get(MultipleSearching2.KEY_ID));
	mobilenumber=(map.get("mobile"));
	email=(map.get("email"));
	contacts=(map.get("contacts"));
	mobilenumber=(map.get("mobile"));
	landline=(map.get("landline"));
	email=(map.get("email"));
	contact.setText("Contacts: "+contacts);
	emailadd.setText("Email Address: "+email);
    imageLoader.DisplayImage(map.get("image"), main_pic);
    
	mCurrentPosition = position;
	   	    	
}

	public void showGallery(int id){
		/*HashMap<String, String> map = AllProperty.mylist.get(id);
		
		String data=consume.getAmmenities(Integer.parseInt(map.get(AllProperty.KEY_ID)));
		 try {
				JSONArray array = new JSONArray(data);
				
				for (int i = 0; i < array.length(); i++) {
					JSONObject e = array.getJSONObject(i);
					images.add(e.getString("url"));
				}
				
			} catch (JSONException e) {
				Log.e("log_tag", "Error parsing data " + e.toString()+"diri jud");
			}finally{
				
			}*/
		 g.setAdapter(new ImageAdapter(getActivity()));
	}

	public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {

        Intent i=new Intent(getActivity(),ViewImage.class);
        startActivity(i);
        
	}
 
    public View makeView() {
        ImageView i = new ImageView(getActivity());
        i.setScaleType(ImageView.ScaleType.FIT_CENTER);
        i.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT));
        
        return i;
    }
 
    private ImageSwitcher mSwitcher;
 
    public class ImageAdapter extends BaseAdapter {
        public ImageAdapter(Context c) {
            mContext = c;
        }
 
        public int getCount() {
            return images.size();
        }
 
        public Object getItem(int position) {
            return position;
        }
 
        public long getItemId(int position) {
            return position;
        }
 
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView i = new ImageView(mContext);
 
            imageLoader.DisplayImage(images.get(position), i);
            Log.e("Url Here:", images.get(position));
            //i.setImageResource(mThumbIds[position]);
            i.setAdjustViewBounds(true);
            i.setLayoutParams(new Gallery.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            //i.setBackgroundResource(R.drawable.picture_frame);
            return i;
        }
 
      private Context mContext;
 
    }
    public class loadImage extends AsyncTask<Void,Void,Void>{
   	
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			
			String data=consume.getAmmenities(prop_id);
			 try {
					JSONArray array = new JSONArray(data);
					
					for (int i = 0; i < array.length(); i++) {
						JSONObject e = array.getJSONObject(i);
						images.add(e.getString("url"));
					}
					
				} catch (JSONException e) {
					Log.e("log_tag", "Error parsing data " + e.toString()+"diri jud");
				}finally{
					
				}
			return null;
		}
		 protected void onPostExecute(Void result) {
			 g.setAdapter(new ImageAdapter(getActivity())); 
		     }
		 
    	
    }
    
    public class Add extends AsyncTask<Void, Void, Void> {

	    private final ProgressDialog dialog = new ProgressDialog(fa);
	    boolean results=false;
    	int person_id=LoginActivity.id;
    	
	    protected void onPreExecute() {

	            this.dialog.setMessage("Loading...");
	            this.dialog.show();
	    }


	    protected Void doInBackground(final Void... unused) {
	    	
			try {
					results=consume.SaveLead(prop_id,person_id);
							
							if(results){
								try {   
									GMailSender sender = new GMailSender("jesonenerez@gmail.com", "jesonenerez");
									sender.sendMail("Favorites",   
											"Somebody is interested with this property of yours: "+name,   
											"jesonenerez@gmail.com",   
											email);
									Log.e("Message", "Na sent bai");
								} catch (Exception e) {   
									Log.e("SendMail", e.getMessage(), e);   
								} 
								

							}
							System.out.println(prop_id+"-"+person_id);
							
				
		
			} catch (Exception e) {
				Log.e("","wala jud ma add",e);
			}
	   
	        return null; 
	    }
	    protected void onPostExecute(Void result) {
			 if(results){
				 Buyer.actionbar.setSelectedNavigationItem(2);
				 
			 }

	    	if (this.dialog!=null) {
	            this.dialog.dismiss();
	            }  
	     }
	  }
    
/*    public class DisableField extends AsyncTask<Void, Void, Void> {

	    protected void onPreExecute() {

	    }
	    protected Void doInBackground(final Void... unused) {
	    	
	    	
	        return null; 
	    }
	    protected void onPostExecute(Void result) {
	    	
	     }
	  }*/

}